// pages/undercover/undercover.js

//获取应用实例
const app = getApp();
// 自定义失败的弹框
function showWordModal(title, content) {
  wx.showWordModal({
    title,
    content,
    showCancel: false
  })
}
// 自定义成功的弹框
function showSuccess(title) {
  wx.showToast({
    title,
    icon: 'success',
    duration: 1000
  })
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    personList: [], //当前房间中的人员列表
    showWordModals: false, //是否显示自定义词语弹框，默认隐藏
    showRuleModals: false, //是否显示游戏规则弹框，默认隐藏
    isStart:false, //游戏状态是否开始
    holderType:1, //当前用户是否为房主
    holderId:0, //房主的id
    ownerId:0,  //用户自己的id
    // loseId:0, //掉线用户的id
    pmword:'', //自定义设置的平民词语
    wdword: '', //自定义设置的卧底词语
    showWord:'', //玩家展示的词语
    setpmword:'', //自定义平民词语
    setwdword: '',//自定义卧底词语
    wdInfo:[], //房主看到的卧底的信息
    selWord: false, //是选择词组中的词语还是自定义的词语，默认取词组
    socketStatus: 'closed',
    personNum :1, //房屋中的人数
    room_id:0, //定义跳转的房间id
    customType:1, //开始游戏的词语来源，1为直接“开始游戏”后台分配词语，2为自定义词语
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function() {
    var that = this;
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route //当前页面url
    var options = currentPage.options //如果要获取url中所带的参数可以查看options
    // console.log(url);
    // console.log(options);
    that.setData({
      room_id:options.room_id,
      ownerId:app.globalData.userInfoSession.uid
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // console.log('触发onshow事件')
    if (this.data.socketStatus === 'closed') {
      this.openSocket()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    // console.log('页面卸载')
    this.closeSocket();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var that=this;
    var str = '/pages/main/home/home?jump=' + that.data.room_id + '&type=2';
    return {
      // title: '谁是卧底' + that.data.room_id,
      title: '谁是卧底',
      // title: str,
      path: str,
      imageUrl:'../../resource/share.png',
      success:function(res){
        console.log(res);
      }
    }
  },
  // 点击分享按钮
  handleTapShareButton() {
    if (!((typeof wx.canIUse === 'function') && wx.canIUse('button.open-type.share'))) {
      wx.showWordModal({
        title: '当前版本不支持转发按钮',
        content: '请升级至最新版本微信客户端',
        showCancel: false
      })
    }
  },

  // 自定义词语
  modalWord() {
    this.setData({
      showWordModals: true
    })
  },
  // 游戏规则
  modalRule(){
    this.setData({
      showRuleModals: true
    })
  },
  // 点击阴影曾关闭弹框
  hideModal() {
    this.setData({
      showWordModals: false,
      showRuleModals: false
    });
  },
  // 弹框确认按钮点击事件
  formSubmit(e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value);
    let civilian = e.detail.value.civilian;
    let undercover = e.detail.value.undercover;
    if (!civilian || !undercover) {
      wx.showToast({
        title: "请补全信息",
        image: "../../../../images/fail.png",
        duration: 4000
      });
    } else {
      this.hideModal();
      wx.showToast({
        title: "游戏开始",
        icon: "success",
        duration: 4000
      });
      this.setData({
        isStart: true,
        selWord: true,
        pmword: civilian,
        wdword: undercover
      });
    }
  },
  //绑定输入词语数目
  setpm(e) {
    this.setData({
      setpmword: e.detail.value
    })
  },
  // 绑定输入时间
  setwd(e) {
    this.setData({
      setwdword: e.detail.value
    })
  },
  // 房主开始游戏按钮
  playGame(){
    var that=this;
    if (this.data.showWordModals) {
      that.setData({
        customType: 1
      })
    } else {
      that.setData({
        customType: 2
      })
    }
    // console.log('开始游戏的参数', that.data.room_id, that.data.customType, that.data.setpmword, that.data.setwdword)
    wx.request({
      method: 'post',
      url: app.globalData.path + 'start_game',
      header: {
        'Cookie': "PHPSESSID=" + app.globalData.session_id
      },
      dataType: 'json',
      data: {
        room_id: that.data.room_id,
        customize:that.data.customType,
        undercover_word: that.data.setwdword,
        civilian_word: that.data.setpmword
      },
      success: function (res) {
        console.log(res);
        that.setData({
          showWordModals:false,
        })
       
      }
    })
  },
  // 房主再来一局
  moreOnce(){
    var that=this;
    wx.request({
      method: 'get',
      url: app.globalData.path + 'again_game',
      header: {
        'Cookie': "PHPSESSID=" + app.globalData.session_id
      },
      dataType: 'json', 
      data: {
        room_id: that.data.room_id,
      },
      success: function (res) {
        that.setData({
          isStart: false,
        });
      }
    })
  },
  // // 发起websocekt
  toggleSocket() {
    if (this.data.socketStatus === 'closed') {
      this.openSocket()
    } else if (this.data.socketStatus === 'connected') {
      const showSuccess = true
      this.closeSocket(showSuccess)
    }
  },
  openSocket() {
    // var socket = this.socket = new qcloud.Tunnel(tunnelUrl)
    var that=this;
    wx.onSocketOpen(() => {
      // console.log('WebSocket 已连接')
      // showSuccess('Socket已连接');

      setInterval(function(){
        that.sendMessage();
      },3000)
      this.setData({
        socketStatus: 'connected',
        waitingResponse: false
      })
    })

    wx.onSocketClose(() => {
      console.log('WebSocket 已断开')
      this.setData({ socketStatus: 'closed' })
      // if(!this.data.isStart){
        app.globalData.isHolder = false;
      // }
    })

    wx.onSocketError(error => {
      showWordModal('发生错误', JSON.stringify(error))
      console.error('socket error:', error)
      this.setData({
        loading: false
      })
    })

    // 监听服务器推送消息
    wx.onSocketMessage(message => {
      var that=this;
      // showSuccess('收到信道消息');
      that.setData({
        loading: false
      })
      var obj = JSON.parse(message.data);
      // console.log('类型为'+obj.type)
      var client_id=obj.client_id;
      // console.log('当前的isHolder为：'+ app.globalData.isHolder)
      if(app.globalData.isHolder){
        that.setData({
          holderType:1
        })
      }else{
        that.setData({
          holderType:2
        })
      }
      switch (obj.type){
        // 初始化数据
        case 'init' :
          wx.request({
            method: 'post',
            url: app.globalData.path + 'enter_room',
            header: {
              'Cookie': "PHPSESSID=" + app.globalData.session_id
            },
            dataType :'json',
            data: {
              room_id: that.data.room_id,
              type: that.data.holderType,
              client_id: client_id
            },
            success:function(res){
              if (res.data.status == 0) {
                wx.showToast({
                  title: res.data.msg,
                  image: "../../../../images/fail.png",
                  // icon:none,
                  duration: 4000
                });
                setTimeout(function () {
                  wx.redirectTo({
                    url: '/pages/main/home/home',
                  })
                }, 2000)
              }
            },
            error:function(res){
              console.log(res.data);
            }
          })
        break;
        // 进入游戏房间
        case 'enter_room':
          var objList = JSON.parse(message.data);
          var PL = that.data.personList;
          console.log('enter_room');
          console.log(objList);
          if(objList.room_status==1){
            that.setData({
              isStart: false
            })
          }
          if(objList.client_list===undefined){ // 房间中的人：新进入房间人的数据
            PL.push({
              client_id: objList.client_id,
              type: 2,
              nickname: objList.nickname,
              avatar_url: objList.avatar_url
            })
            for (var i = 0; i < objList.length; i++) {
              if (objList[i].type == 1) {
                that.setData({
                  holderId: objList[i].uid
                })
              }
            }
            that.setData({
              personList:PL
            })
            wx.showToast({
              title: objList.nickname + '加入了房间',
              icon:'none',
              duration:2000
            })
          } else {// 普通玩家进入房间：此时房间中全部的人员数据
            for (var i = 0; i < objList.client_list.length; i++) {
              if (objList.client_list[i].type == 1) {
                that.setData({
                  holderId: objList.client_list[i].uid
                })
              }
            }
            that.setData({
              personList: objList.client_list
            })
          }
        break;
        // 退出房间
        case 'exit_room':
          var objList = JSON.parse(message.data);
          var PL = that.data.personList;
          console.log('exit_room');
          console.log(objList);
          if (that.data.isStart) {
            wx.showToast({
              title: objList.nickname + '掉线了',
              icon: 'none',
              duration: 2000
            })
            // loseId: objList.client_id
          } else {
              // 删掉掉线的人的头像
            for (var i = 0; i < PL.length; i++) {
              if (PL[i].client_id == objList.client_id) {
                PL.splice(i, 1);
              }
            }
            that.setData({
              personList: PL,
            })
            wx.showToast({
              title: objList.nickname + '退出了房间',
              icon: 'none',
              duration: 2000
            })
          }
        break;
        // 游戏中退出房间后重新回到房间
        case 'reconnect_room':
          var objList = JSON.parse(message.data);
          console.log('reconnect_room');
          console.log(objList);
          // 重新对连线的用户进行页面渲染
          wx.showToast({
            title: objList.nickname + '已连线',
            icon: 'none',
            duration: 2000
          })
          for (var i = 0; i < objList.start_list.length;i++){
            if (objList.start_list[i].type==1){
              that.setData({
                holderId: objList.start_list[i].uid   //房主ID
              })
            }
          }
          console.log('房主的id为'+that.data.holderId)
          console.log('当前用户的id为'+that.data.ownerId)
          that.setData({
            personList: objList.start_list,
            isStart: true,
          })
          var clivilian_word = objList.old_user.civilian_word;
          var undercover_word = objList.old_user.undercover_word;
          var curId = objList.uid;
          if(clivilian_word != '' && undercover_word != ''){  // 房主重新连接
            that.setData({
              pmword: clivilian_word,
              wdword: undercover_word,
              wdInfo: objList.old_user.undercover_arr
            })
          } else if (clivilian_word != '' && undercover_word == ''){ //平民返回房间
            if (that.data.ownerId==curId){
              that.setData({
                showWord: clivilian_word,
              })
            }
          } else if (clivilian_word == '' && undercover_word != ''){ //卧底返回房间
            if (that.data.ownerId == curId) {
              that.setData({
                showWord: undercover_word,
              })
            }
          }
        break;
        //游戏未开始，房主掉线
        case 'change_homeowner':  
          app.globalData.isHolder = false;
          var objList = JSON.parse(message.data);
          var PL = objList.client_list;
          console.log('changge_homeowner');
          console.log(objList);
          for(var i=0;i<PL.length;i++){
            if(PL[i].type==1){
              that.setData({
                holderType:1,
                holderId: PL[i].uid
              })
            }
          }
          that.setData({
            personList: PL,
          })
          wx.showToast({
            title: '房主退出了房间',
            icon: 'none',
            duration: 2000
          })
        break;
        //开始游戏-房主返回值
        case 'homeowner':  
          console.log(obj);
          that.setData({
            isStart: true,
            pmword: obj.civilian_word,
            wdword: obj.undercover_word,
            wdInfo: obj.undercover_arr
          })
        break;
        //开始游戏-房主返回值
        case 'undercover':  
          console.log(obj);
          that.setData({
            showWord: obj.word,
            isStart: true,
            holderType:2
          })
        break;
        //开始游戏-房主返回值
        case 'civilian':  
          console.log(obj);
          that.setData({
            showWord: obj.word,
            isStart: true,
            holderType:2
          })
        break;
        // 再来一次游戏
        case 'again_game':
          var objList = JSON.parse(message.data);
          console.log(objList)
          that.setData({
            isStart: false,
            personList: objList.client_list
          })
        break;
      }
    })

    // 打开信道
    wx.connectSocket({
      url: 'ws://192.168.1.189:7272',
    })
  },

  closeSocket() {
    if (this.data.socketStatus === 'connected') {
      wx.closeSocket({
        success: () => {
          showSuccess('Socket已断开')
          this.setData({ socketStatus: 'closed' })
          app.globalData.isHolder = false;
        }
      })
    }
  },
  sendMessage() {
    if (this.data.socketStatus === 'connected') {
      console.log('向后台发送一条请求');
      wx.sendSocketMessage({
        data: '{"type":"heart","message":"heart_message..."}'
      })
    }
  }
})